//
//  JMPickerSelectionView.m
//  NewiOSProject
//
//  Created by li on 2023/9/6.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMPickerSelectionView.h"
#import "UIView+PopupProtocol.h"
#import "PaddingView.h"
#import "LayoutScrollView.h"
#import "JMPickerSelectionModel.h"


@interface JMPickerSelectionView ()<UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate>

@property(nonatomic, strong, nonnull) UIStackView *rootStackView;
/// 单选选择的对象
@property(nonatomic, strong) JMPickerSelectionModel *selectedData;
/// 日期选择器的选中的对象
@property(nonatomic, strong) NSDate *selectedDate;
/// 内容选择器
@property(nonatomic, strong, nonnull) UIPickerView *pickerView;
/// 日期选择器
@property(nonatomic, strong) NSArray *days;
@property(nonatomic, strong) NSArray *months;
@property(nonatomic, strong) NSArray *years;
@property(nonatomic, assign) NSInteger curDay;
@property(nonatomic, assign) NSInteger curYear;
@property(nonatomic, assign) NSInteger curMonth;

@end

@implementation JMPickerSelectionView
@synthesize modalStyle;
@synthesize translucentView;
@synthesize dismissCompletion;

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.translucentView = [self defaultTranslucentView];
        
        self.modalStyle = PopupViewModalStyleFromBottom;
        [self setupViews];
        self.backgroundColor = [UIColor whiteColor];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:(UIKeyboardWillShowNotification) object: nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object: nil];
    }
    return self;
}
-(void)setAuthModel:(JMAuthCellModel *)authModel{
    _authModel = authModel;
    if ([authModel.actionType isEqualToString:@"Birthday_Focus"]) {
        self.type=0;
    }else if([authModel.actionType isEqualToString:@"Bank_Name_Focus"]){
        self.type = 6;
    }else{
        self.type = 1;

    }
}

- (void)setupViews {
    
    UIStackView *rootStack = [UIStackView new];
    self.rootStackView = rootStack;
    rootStack.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    rootStack.translatesAutoresizingMaskIntoConstraints = NO;
    rootStack.axis = UILayoutConstraintAxisVertical;
    rootStack.alignment = UIStackViewAlignmentCenter;
    rootStack.spacing = 0;
    [self addSubview:rootStack];
    [NSLayoutConstraint activateConstraints:@[
        [rootStack.leftAnchor constraintEqualToAnchor:self.leftAnchor],
        [rootStack.rightAnchor constraintEqualToAnchor:self.rightAnchor],
        [rootStack.topAnchor constraintEqualToAnchor:self.topAnchor],
        [rootStack.bottomAnchor constraintEqualToAnchor:self.bottomAnchor],
    ]];
    
    UIStackView *control = [UIStackView new];
    control.axis = UILayoutConstraintAxisHorizontal;
    [control.widthAnchor constraintEqualToConstant: kScreenWidth].active = YES;
    [rootStack addArrangedSubview:control];
    
    UIButton *cancel = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [cancel setTitle:@"Cancelar" forState:(UIControlStateNormal)];
    [cancel setTitleColor:[UIColor colorWithHexString:@"#9B9B9B"] forState:(UIControlStateNormal)];
    cancel.titleLabel.font = [UIFont systemFontOfSize:14];
    cancel.userInteractionEnabled = NO;
    [control addArrangedSubview: [[PaddingView initWithContentView:cancel edgeInsets:(UIEdgeInsetsMake(20, 20, 20, 20))] then:^(PaddingView * _Nonnull view) {
        [view.heightAnchor constraintEqualToConstant:60].active = YES;
        WeakSelf
        [view addTapGestuer:^(UIView * _Nonnull view) {
            [weakSelf dismissPopup];
        }];
    }]];
    
    [control addArrangedSubview: [UIView new]];
    
    UIButton *confirm = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [confirm setTitle:@"Confirmar" forState:(UIControlStateNormal)];
    [confirm setTitleColor:[UIColor colorWithHexString:@"#0F1511"] forState:(UIControlStateNormal)];
    confirm.titleLabel.font = [UIFont systemFontOfSize:14];
    confirm.userInteractionEnabled = NO;
    WeakSelf
    [control addArrangedSubview: [[PaddingView initWithContentView:confirm edgeInsets:(UIEdgeInsetsMake(20, 20, 20, 20))] then:^(PaddingView * _Nonnull view) {
        [view addTapGestuer:^(UIView * _Nonnull view) {
            [weakSelf dismissPopup];
            [weakSelf confirmDateSelection];
        }];
    }]];
    
    UIStackView *searchStack = [[UIStackView alloc]init];
    searchStack.axis = UILayoutConstraintAxisHorizontal;
    searchStack.alignment = UIStackViewAlignmentCenter;
    searchStack.spacing = 10;
    
    UIImageView *searchImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search.png"]];
    searchImageView.contentMode = UIViewContentModeScaleAspectFit;
    [searchImageView.widthAnchor constraintEqualToConstant:20].active = YES;
    [searchStack addArrangedSubview: searchImageView];
    
    self.searchTextField = [UITextField new];
    self.searchTextField.placeholder = @"HSBC México";
    self.searchTextField.font = [UIFont systemFontOfSize:14];
    self.searchTextField.textColor = [UIColor colorNamed:@"#0F1511"];
    self.searchTextField.textAlignment = NSTextAlignmentCenter;
    self.searchTextField.returnKeyType = UIReturnKeySearch;
    self.searchTextField.delegate = self;
    [self.searchTextField.heightAnchor constraintEqualToConstant:46].active = YES;
    [searchStack addArrangedSubview:self.searchTextField];
    
    
    [rootStack addArrangedSubview: [[PaddingView initWithContentView:searchStack edgeInsets:(UIEdgeInsetsMake(0, 13, 0, 13))] then:^(PaddingView * _Nonnull view) {
        
        weakSelf.searchPaddingView = view;
        view.layer.cornerRadius = 12;
        view.backgroundColor = [UIColor colorWithHexString:@"#F4F4F4"];
        //        [view.heightAnchor constraintEqualToConstant:46].active = YES;
        [view.widthAnchor constraintEqualToConstant:kScreenWidth - 40].active = YES;
    }]];
    self.searchPaddingView.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:self.searchTextField];
    
    UIPickerView *picker = [UIPickerView new];
    self.pickerView = picker;
    picker.delegate = self;
    picker.dataSource = self;
    [picker.heightAnchor constraintEqualToConstant:250].active = YES;
    [rootStack addArrangedSubview: [PaddingView initWithContentView:picker edgeInsets:(UIEdgeInsetsMake(20, 0, 20, 0))]];
    
    
    [rootStack addArrangedSubview:[PaddingView initWithContentView:self.pickerView edgeInsets:UIEdgeInsetsMake(20, 0, 20, 0)]];
    
    
}
- (void)textFieldDidChangeValue:(NSNotification *)notification
{
    UITextField *sender = (UITextField *)[notification object];
    NSString *inputContent = sender.text;
    [self.filteredArray removeAllObjects];
    [self.pickerView selectedRowInComponent:0];
    if (inputContent.length > 0) {
        for (JMPickerSelectionModel*mod in self.list) {
            if ([mod.label containsString:inputContent]) {
                [self.filteredArray addObject:mod];
            }
        }
        self.selectedData = self.filteredArray.firstObject;
    } else {
        // 如果输入内容为空，直接将原始数据复制到结果数组
        self.selectedData = self.list.firstObject;
        [self.filteredArray addObjectsFromArray:self.list];
    }
    
    [self.pickerView reloadAllComponents];
}
#pragma mark - keyboard 监听
- (void)keyboardWillShow: (NSNotification *)aNofitication {
    [self.rootStackView setCustomSpacing: 100 afterView:self.searchPaddingView];
}

- (void)keyboardWillDismiss: (NSNotification *)aNofitication {
    UIEdgeInsets edgeInsets = self.searchPaddingView.edgeInsets;
    [self.rootStackView setCustomSpacing: 0 afterView: self.searchPaddingView];
}

- (void)popup:(UIView *)rootView edgeInsets:(UIEdgeInsets)edgeInsets {
    
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    [super popup:rootView edgeInsets:edgeInsets];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    NSInteger n = -1;
    for (NSInteger i = 0; i < self.list.count; i ++) {
        
        JMPickerSelectionModel *model = self.list[i];
        if ([model.label isEqualToString:textField.text]) {
            n = i;
            break;
        }
    }
    
    if (n >= 0 && n < self.list.count) {
        
        [self.pickerView selectRow:n inComponent:0 animated:YES];
        if (self.filteredArray.count) {
            self.selectedData = self.filteredArray[n];
        }else{
            self.selectedData = self.list[n];
        }
    }
    
}

#pragma mark - UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if (self.type==0) {
        return 3;
    }else{
        return  1;
    }
    
}
-(NSArray *)days{
    return [self createDaysArrayForMonth:self.curMonth andYear:self.curYear];
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (self.type==0) {
        if (component==0) {
            return self.days.count;
        }else if(component==1){
            return self.months.count;
        }else{
            return self.years.count;
        }
    }else{
        if (self.type==6) {
            return self.filteredArray.count;
        }else{
            return self.list.count;
        }
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (self.type==0) {
        if (component == 0) {
            return self.days[row];
        } else if (component == 1) {
            return self.months[row]; // 月份（阿拉伯数字）
        } else {
            return self.years[row]; // 年份
        }
        
    }else{
        JMPickerSelectionModel *model;
        if (self.type==6) {
            if (self.filteredArray.count) {
                model = self.filteredArray[row];
            }else{
                model = self.list[row];
            }
        }else{
            model = self.list[row];
        }
        return model.label;
    }
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (self.type==0) {
        if (component==0) {
            NSString *day = self.days[row];
            self.curDay = day.integerValue;
        }
        if (component==1) {
            NSString *mon = self.months[row];
            self.curMonth = mon.integerValue;
        }
        if (component==2) {
            NSString *year = self.years[row];
            self.curYear = year.integerValue;
        }
        
        self.selectedDate = [self dateFromYear:self.curYear month:self.curMonth day:self.curDay];
        NSLog(@"%ld-%ld-%ld",self.curDay,self.curMonth,self.curYear);
        NSLog(@"%@",self.selectedDate);
        [self.pickerView reloadComponent:0];
    }else if (self.type==6) {
        if (self.filteredArray.count) {
            self.selectedData = self.filteredArray[row];
        }else{
            self.selectedData = self.list[row];
        }
    }else{
        if (self.list.count) {
            self.selectedData = self.list[row];
        }
    }
}
- (NSDate *)dateFromYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    // 创建一个日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // 创建一个NSDateComponents对象并设置年、月和日
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    
    // 使用日历对象将NSDateComponents转换为NSDate
    NSDate *date = [calendar dateFromComponents:components];
    
    return date;
}


#pragma mark - 日期选择
- (void)datePickerSelected: (UIDatePicker *)datePicker {
    self.selectedDate = datePicker.date;
    NSLog(@"%@", datePicker.date);
}

#pragma mark - 确认事件
- (void)confirmDateSelection {
    if (self.type==0) {
        if (self.confirmDateCallback) {
            if (self.selectedDate == nil) {
                self.selectedDate = [NSDate new];
            }
            self.confirmDateCallback(self.selectedDate);
        }
    }else{
        if (self.list.count == 0) {
            
            if (self.confirmCallback) {
                self.confirmCallback(self.selectedData);
            }
            return;
        }
        if (self.selectedData == nil) {
            if (self.filteredArray.count) {
                self.selectedData = self.filteredArray.firstObject;
            }else{
                self.selectedData = self.list.firstObject;
            }
        }
        
        if (self.confirmCallback) {
            self.confirmCallback(self.selectedData);
        }
    }
    
}


#pragma mark - 网络请求

/// 获取 性别, 城市, 婚姻状况, 孩子个数, 教育程度 的弹框数据
- (void)requestPopupData {
    if ([self.authModel.actionType isEqualToString:@"Overdue_Focus"]) {
        [self clearSingleSelectionPickerData];
        for(NSInteger i = 0; i < 2; i ++) {
            JMPickerSelectionModel *model = [JMPickerSelectionModel new];
            if (i == 0) {
                model.label = @"No";
                model.value = @"1";
            }else {
                model.label = @"Sí";
                model.value = @"2";
            }
            [self.list addObject:model];
        }
    }else if ([self.authModel.actionType isEqualToString:@"Overdue_Days_Focus"]) {
        [self clearSingleSelectionPickerData];
        for (NSInteger i = 0; i < 31; i ++) {
            JMPickerSelectionModel *model = [JMPickerSelectionModel new];
            model.label = [NSString stringWithFormat:@"%ld días", i];
            model.value = [NSString stringWithFormat:@"%ld", i +  1];
            [self.list addObject:model];
        }
    } else if ([self.authModel.actionType isEqualToString:@"Loan_Total_Focus"]) {
        for (NSInteger i = 0; i < 4; i ++) {
            JMPickerSelectionModel *model = [JMPickerSelectionModel new];
            if (i == 0) {
                model.label = @"$0 ~ $500";
                model.value = @"1";
            }else if (i == 1) {
                model.label = @"$500 ~ $1000";
                model.value = @"2";
            }else if (i == 2) {
                model.label = @"$1000 ~ $3000";
                model.value = @"3";
            }else if (i == 3) {
                model.label = @"$3000 ~";
                model.value = @"4";
            }
            [self.list addObject:model];
        }
    }else if ([self.authModel.actionType isEqualToString:@"Loan_Count_Focus"] ||
              [self.authModel.actionType isEqualToString:@"Loan_Repayment_Focus"]) {
        for (NSInteger i = 0; i < 12; i ++) {
            JMPickerSelectionModel *model = [JMPickerSelectionModel new];
            model.label = [NSString stringWithFormat:@"%ld", i];
            model.value = [NSString stringWithFormat:@"%ld", i +  1];
            [self.list addObject:model];
        }
    }else if ([self.authModel.actionType isEqualToString:@"Salary_Day1_Focus"] ||
              [self.authModel.actionType isEqualToString:@"Salary_Day2_Focus"]) {
        for (NSInteger i = 1; i <= 31; i ++) {
            JMPickerSelectionModel *model = [JMPickerSelectionModel new];
            model.label = [NSString stringWithFormat:@"%ld", i];
            model.value = [NSString stringWithFormat:@"%ld", i];;
            [self.list addObject:model];
        }
    } else {
        NSString *urlPath = @"/api/common/dict-list";
        if (self.type==6) {
            urlPath = @"/api/common/bank-list";
        }
        NSDictionary *dic = @{
            @"type": self.authModel.typeString
        };
        
        [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(urlPath) params:dic success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
                        
            if (dataDic != nil) {
                if (self.type == 6) {
                    NSArray *dictList = (NSArray *)[dataDic safeArrayForKey:@"banks"];
                    if (dictList != nil) {
                        for (NSDictionary *item in dictList) {
                            if (item != nil) {
                                NSString *bankCode = (NSString *)item[@"bankCode"];
                                NSString *bankName = (NSString *)item[@"bankName"];
                                
                                JMPickerSelectionModel *model = [JMPickerSelectionModel new];
                                model.label = [NSString stringWithFormat:@"%@", bankName];
                                model.value = [NSString stringWithFormat:@"%@", bankCode];
                                [self.list addObject:model];
                            }
                        }
                        [self.filteredArray addObjectsFromArray:self.list];
                    }
                }else {
                    NSArray *dictList = (NSArray *)[dataDic safeArrayForKey:@"dictList"];
                    if (dictList != nil) {
                        for (NSDictionary *item in dictList) {
                            if (item != nil) {
                                NSString *typeName = (NSString *)item[@"typeName"];
                                NSString *remark = (NSString *)item[@"remark"];
                                
                                JMPickerSelectionModel *model = [JMPickerSelectionModel new];
                                model.label = [NSString stringWithFormat:@"%@", remark];
                                model.value = [NSString stringWithFormat:@"%@", typeName];
                                if (self.type==5) {
                                    model.label = typeName;
                                }
                                [self.list addObject:model];
                            }
                        }
                    }
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.pickerView reloadAllComponents];
            });
            
        } fail:^(NSString * _Nonnull errorMsg) {
        }];
    }
    
}

#pragma mark - 懒加载

- (NSMutableArray<JMPickerSelectionModel *> *)list {
    if (!_list) {
        self.list = [NSMutableArray array];
    }
    return _list;
}
- (NSMutableArray<JMPickerSelectionModel *> *)filteredArray {
    if (!_filteredArray) {
        _filteredArray = [NSMutableArray array];
    }
    return _filteredArray;
}

- (void)setType:(NSInteger)type {
    _type = type;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self configureDataList];
    });
}

- (void)clearSingleSelectionPickerData {
    
    [self.list removeAllObjects];
    [self.pickerView reloadAllComponents];
}

- (void)configureDataList {
    if (self.type==0) {
        // 初始化日和月数组
        
        // 初始化月份和年份数组，使用阿拉伯数字
        self.months = @[@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"11", @"12"];
        self.curDay = 1;
        self.curMonth = 1;
        // 生成年份数组，从当前年份往前200年
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *currentYearComponents = [calendar components:NSCalendarUnitYear fromDate:[NSDate date]];
        NSInteger currentYear = [currentYearComponents year];
        self.curYear = currentYear;
        NSMutableArray<NSString *> *yearsArray = [NSMutableArray array];
        for (NSInteger i = currentYear-18; i >=currentYear-45; i--) {
            [yearsArray addObject:[NSString stringWithFormat:@"%ld", (long)i]];
        }
        self.years = yearsArray;
        NSString *year  = yearsArray.firstObject;
        self.curYear = year.integerValue;
        self.selectedDate = [self dateFromYear:self.curYear month:self.curMonth day:self.curDay];
    }else{
        [self requestPopupData];
    }
    
    [self.pickerView reloadAllComponents];
}

- (NSArray<NSString *> *)createDaysArrayForMonth:(NSInteger)month andYear:(NSInteger)year {
    NSMutableArray<NSString *> *daysArray = [NSMutableArray array];
    NSInteger daysInMonth = 31; // 默认为31天
    
    if (month == 2) {
        // 对于2月，根据年份判断是闰年还是非闰年
        if ([self isLeapYear:year]) {
            daysInMonth = 29; // 闰年2月有29天
        } else {
            daysInMonth = 28; // 非闰年2月有28天
        }
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        daysInMonth = 30; // 4月、6月、9月和11月都是30天
    }
    
    for (int day = 1; day <= daysInMonth; day++) {
        [daysArray addObject:[NSString stringWithFormat:@"%d", day]];
    }
    
    return daysArray;
}

- (BOOL)isLeapYear:(NSInteger)year {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        return YES;
    } else {
        return NO;
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
